<template>
  <div>
    <!-- 面包屑导航区 -->
    <hamburger :secTitle="secTitle" :thirdTitle="thirdTitle"></hamburger>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <el-button type="info" plain @click="dialogVisible=true">添加角色</el-button>
      <!-- 表格区域 -->
      <el-table border stripe :data="roleList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['border',{'topBoder':i1==0},'vcenter']">
              <el-col :span="6">
                <el-tag closable @close="removeTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[{'topBoder':i2!==0},'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeTag(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      @close="removeTag(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="success"
              icon="el-icon-delete"
              size="small"
              @click="removeRole(scope.row.id)"
            >删除</el-button>
            <el-button
              type="info"
              icon="el-icon-setting"
              size="small"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加对话框 -->
      <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="closeDialog">
        <el-form
          label-width="100px"
          :model="addRoleForm"
          :rules="addRoleRules"
          ref="addRoleFormRef"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改对话框 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="closeEditDialog">
        <el-form
          label-width="100px"
          :rules="addRoleRules"
          :model="editRoleForm"
          ref="editRoleFormRef">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配对话框 -->
      <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
        <el-tree
          :data="rightList"
          :props="defaultProps"
          default-expand-all
          show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
        ></el-tree>
        <span slot="footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRight">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      secTitle: '权限管理',
      thirdTitle: '角色列表',
      roleList: [],
      rightList: [],
      defKeys:[],
      roleId:'',
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      dialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleRules: {
        roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }]
      },
      editRoleForm: {
        roleName: '',
        roleDesc: '',
        roleId: ''
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      } else {
        this.$message.success('获取角色列表成功')
        this.roleList = res.data
      }
    },
    closeDialog() {
      this.$refs.addRoleFormRef.resetFields()
    },
    addRole() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        } else {
          this.$message.success('添加角色成功')
          this.dialogVisible = false
          this.getRoleList()
        }
      })
    },
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败')
      } else {
        this.$message.success('获取角色信息成功')
        this.editRoleForm = res.data
      }
    },
    closeEditDialog() {
      this.$refs.editRoleFormRef.resetFields()
    },
    editRole() {
      // this.$refs.editRoleFormRef 获取到表单
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整的角色信息')
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          this.editRoleForm
        )
        // console.log(res)
        // console.log(typeof this.editRoleForm.roleId)
        if (res.meta.status !== 200) {
          return this.$message.error('修改角色失败')
        } else {
          this.$message.success('修改角色成功')
          this.editDialogVisible = false
          this.getRoleList()
        }
      })
    },
    async removeRole(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除角色')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      } else {
        this.$message.success('删除角色成功')
        this.getRoleList()
      }
    },
    async removeTag(role, rightId) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('取消删除该权限')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      } else {
        this.$message.success('删除权限成功')
        role.children = res.data
      }
    },
    async showSetRightDialog(role) {
      this.roleId=role.id
      this.setRightDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      } 
        // this.$message.success('获取权限列表成功')
        this.rightList = res.data
        //调用getDefKeys进行递归，将三级权限添加到数组中
        this.getDefKeys(role,this.defKeys)
        console.log(role)
        console.log(this.defKeys)
    },
    getDefKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }else{
        //递归调用
        node.children.forEach(item=>this.getDefKeys(item,arr))
      }
    },
    setRightDialogClosed(){
      this.defKeys=[]
    },
    async addRight(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idkeys = keys.join(',')
      console.log(idkeys)
      const {data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idkeys})
      if(res.meta.status!==200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightDialogVisible=false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.border {
  border-bottom: 1px solid #eee;
}
.topBoder {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>